/**
 * Created by wry on 2015/4/13.
 */
var Users = mongoose.model('user');
var async = require('async');
var neighbourActivity = mongoose.model('activity_neighbour');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var Question = mongoose.model('question');
var Community = mongoose.model('community');

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };
}
function commentToString(f) {
    return f.toString().
        replace(/^[^\/]+\/\*!?/, '').
        replace(/\*\/[^\/]+$/, '');
}
function sqlConditionString(conditionList) {
    var len = conditionList.length
    if (len == 0)
        return ''
    var condition = "where "

    for (var i = 0; i < len; i++) {
        condition += conditionList[i]
        if (i != len - 1)
            condition += ' and '
    }
    return condition
}

exports.getClickSourceService = function (startDate, endDate, callback) {

    var conditionList = []
    if (startDate != 'all')
        conditionList.push("CASE when create_time > 10000000000 then from_unixtime(create_time / 1000) else from_unixtime(create_time) end >='{0}'".format(startDate))
    if (endDate != 'all')
        conditionList.push("CASE when create_time > 10000000000 then from_unixtime(create_time / 1000) else from_unixtime(create_time) end <='{0}'".format(endDate))

    var dateConditions = sqlConditionString(conditionList)

    var sql = commentToString(function () {
        /*
         SELECT count(*) total, log.click_source, logdesc.click_desc
         FROM
         66xiaoqu_log.log_read as log left join 66xiaoqu_log.log_read_desc as logdesc on log.click_source = logdesc.click_source
         {0}
         group by log.click_source
         */
    }).format(dateConditions)
    //logger.info(sql)

    mysqlUtil.queryBI(sql, function (err, result) {
        callback(err, result)
    })
}
